package com.cx;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

public class InsertDataBatch {
    public static void main(String[] args) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/test2?useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "root"; // 替换为你的MySQL密码

        // SQL插入语句
        String insertSql = "INSERT INTO users (name, age, city, email) VALUES (?, ?, ?, ?)";

        // 创建随机数据生成器
        Random random = new Random();

        try (Connection conn = DriverManager.getConnection(url, user, password);

             PreparedStatement pstmt = conn.prepareStatement(insertSql)) {

            // 插入一百万条数据
            for (int i = 0; i < 1000000; i++) {
                // 生成随机数据
                String name = generateRandomString(10);
                int age = 18 + random.nextInt(43); // 年龄范围18到60
                String city = randomCity();
                String email = generateRandomString(10) + "@example.com";

                // 设置参数
                pstmt.setString(1, name);
                pstmt.setInt(2, age);
                pstmt.setString(3, city);
                pstmt.setString(4, email);

                // 添加到批处理
                pstmt.addBatch();

                // 每1000条数据执行一次批量插入
                if ((i + 1) % 1000 == 0) {
                    pstmt.executeBatch();
                    pstmt.clearBatch();
                }
            }

            // 插入剩余的数据
            pstmt.executeBatch();

            System.out.println("数据插入完成！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 生成随机字符串
    private static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }
        return sb.toString();
    }

    // 随机选择城市
    private static String randomCity() {
        String[] cities = {"Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Chengdu"};
        Random random = new Random();
        return cities[random.nextInt(cities.length)];
    }
}